package com.thinkit.security.custom;

import com.thinkit.core.constant.SecurityConstants;
import com.thinkit.core.handler.CustomException;
import com.thinkit.nosql.base.BaseRedisService;
import com.thinkit.utils.model.ApiResult;

public class CustomRiskCheckBase {

    protected BaseRedisService baseRedisService;


    protected void initRedis(BaseRedisService baseRedisService){
        this.baseRedisService = baseRedisService;
    }

    protected void checkerLicense(){

    }

    protected void clearErrorLog(String userName){
        String key = SecurityConstants.ERROR_INPUT_PASS + userName;
        baseRedisService.remove(key);
    }

    protected void writeErrorLog(String userName) {
        String key = SecurityConstants.ERROR_INPUT_PASS + userName;
        long expireTime = baseRedisService.getExpire(key);
        if (expireTime == -1) {
            baseRedisService.increment(key, 1, 600);
        } else {
            baseRedisService.increment(key, 1);
        }
    }

    protected void checkMaxError(String userName) throws CustomException {
        String key = SecurityConstants.ERROR_INPUT_PASS + userName;
        if (baseRedisService.hasKey(key)) {
            Integer times = (Integer) baseRedisService.get(key);
            if (times >= 6) {
                long expireTime = baseRedisService.getExpire(key);
                if (expireTime == -1) {
                    baseRedisService.setExpireTime(SecurityConstants.ERROR_INPUT_PASS + userName, 300L);
                }
                throw new CustomException(ApiResult.result(7001));
            }
        }
    }

}
